package org.jing.core.comp;

import org.jing.core.lang.JingException;
import org.jing.core.util.ClassUtil;
import org.jing.core.util.StringUtil;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Description: 组件库 <br>
 *
 * @author bks <br>
 * @since 2024-01-29 <br>
 */
public class Components {
    private static final ConcurrentHashMap<Class, Object> INSTANCE_MAP = new ConcurrentHashMap<>();

    private Components() {}

    public static <T> T getInstance(Class<T> type) {
        JComponent jComponent = type.getAnnotation(JComponent.class);
        if (null == jComponent) throw new JingException("JComponent missed");
        String compName = StringUtil.ifEmpty(jComponent.value(), type.getSimpleName()).toLowerCase();
        T instance;
        switch (jComponent.type()) {
            case SINGLETON: {
                if (!INSTANCE_MAP.containsKey(type)) {
                    synchronized (INSTANCE_MAP) {
                        INSTANCE_MAP.put(type, instance = (T) createInstance(type));
                    }
                }
                else {
                    instance = (T) INSTANCE_MAP.get(type);
                }
            }
            break;
            case MULTIPLY: {
                instance = (T) createInstance(type);
            }
            break;
            default: {
                instance = null;
                break;
            }
        }
        return instance;
    }

    @SuppressWarnings("UnnecessaryLocalVariable")
    private static Object createInstance(Class<?> type) {
        Object instance = ClassUtil.createInstance(type);
        // 可拓展注册方法, 但其实感觉没必要
        return instance;
    }
}
